import requests
from lxml import etree
import json
import os

bv=input('请输入BV号:')

url = f"https://www.bilibili.com/video/{bv}"

headers = {
    'referer': 'https://www.bilibili.com/',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'
}

res = requests.get(url=url, headers=headers).text
tree = etree.HTML(res)
title = tree.xpath('//*[@id="viewbox_report"]/h1/text()')[0]  # 获取视频标题
json_data = json.loads(tree.xpath('/html/head/script[3]/text()')[0].split('window.__playinfo__=')[1])
accept_description = json_data['data']['accept_description']  # 视频清晰度
audio_url = json_data['data']['dash']['audio'][0]['base_url']  # 音频地址
video_url = json_data['data']['dash']['video'][0]['base_url']  # 视频地址
audio_content = requests.get(url=audio_url, headers=headers).content
video_content = requests.get(url=video_url, headers=headers).content
with open('audio.mp3', mode='wb') as f:
    f.write(audio_content)
with open('video.mp4', mode='wb') as f:
    f.write(video_content)
os.system(f'ffmpeg -i video.mp4 -i audio.mp3 -c copy E:/videos/{title}.mp4')
os.remove('audio.mp3')
os.remove('video.mp4')
print('下载完成')
